package tts.controller.users;

import org.springframework.beans.factory.annotation.Autowired;

import tts.controller.RedirectAction;
import tts.dao.RolesHome;
import tts.dao.UsersHome;
import tts.model.Users;

public class Register extends RedirectAction {

	//fields
	private static final long serialVersionUID = -9037931792240948793L;
	@Autowired
	private UsersHome usersHome;
	@Autowired
	private RolesHome rolesHome;
	private Users userReg;
	private String confirmPwdReg;
	
	//get & set
	public Users getUserReg() {
		return userReg;
	}
	public void setUserReg(Users userReg) {
		this.userReg = userReg;
	}
	public String getConfirmPwdReg() {
		return confirmPwdReg;
	}
	public void setConfirmPwdReg(String confirmPwdReg) {
		this.confirmPwdReg = confirmPwdReg;
	}
	
	//methods
	public String register() {
		try {
			this.userReg.setEnabled(true);
			this.userReg.getRolesList().add(rolesHome.getUserRole());
			this.usersHome.insert(this.userReg);
		} catch (RuntimeException e) {			
			if (e.getClass().getSimpleName().equals("PersistenceException"))
				addFieldError("userReg.username", getText("val.duplicate.user"));
			else addActionError(e.getMessage());
			this.setPage("registration");
			return ERROR;
		}
		addActionMessage(getText("registration.completed"));
		return SUCCESS;
	}
}